#include <iostream>
#include <cstdio>
#include <string>
#include "ASTNode.h"
#include "SymbolTable.h"
#include "CodeGenerator.h"
#include "Optimizer.h"
#include "typecheck.h"

extern int yyparse();
extern FILE* yyin;
extern ASTNode* root;

int main(int argc, char **argv) {
    std::cerr << "[main] enter main()" << std::endl;
    // 支持重定向输入输出，方便本地测试
    // 用法：./compiler < input_file.tc > output_file.s
    // 或者：./compiler test.c
    // 或者：./compiler -opt test.c (启用优化)

    bool enableOptimization = false;
    std::string inputFile;

    // 解析命令行参数
    for (int i = 1; i < argc; i++) {
        std::string arg = argv[i];
        if (arg == "-opt") {
            enableOptimization = true;
        } else if (arg[0] != '-') {
            // 非选项参数，应该是输入文件
            if (inputFile.empty()) {
                inputFile = arg;
            }
        }
    }

    // 设置输入源
    if (!inputFile.empty()) {
        // 有命令行参数指定的文件，从文件读取
        FILE* file = fopen(inputFile.c_str(), "r");
        if (!file) {
            std::cerr << "Error: Cannot open file '" << inputFile << "'" << std::endl;
            return 1;
        }
        yyin = file;
        std::cerr << "[main] input file opened: " << inputFile << std::endl;
    } else {
        // 没有命令行参数，从标准输入读取
        yyin = stdin;
        std::cerr << "[main] using stdin as input" << std::endl;
    }
    std::cerr << "[main] before yyparse" << std::endl;
    yyparse();
    std::cerr << "[main] after yyparse, root=" << root << std::endl;

    if (root) {
        std::cerr << "[main] before typecheck" << std::endl;
        // 类型检查
        TypeChecker typeChecker;
        typeChecker.check(root);
        std::cerr << "[main] after typecheck" << std::endl;
        // 构建符号表
        SymbolTableBuilder symbolBuilder;
        std::cerr << "[main] before symbolBuilder.build" << std::endl;
        symbolBuilder.build(root);
        std::cerr << "[main] after symbolBuilder.build" << std::endl;

                // 根据参数决定是否应用优化器
        if (enableOptimization) {
            std::cerr << "[main] before optimizer" << std::endl;
            std::cerr << "Optimization enabled - using adaptive optimization" << std::endl;
            Optimizer optimizer;

            // 启用自适应优化，根据代码特征自动选择优化策略
            optimizer.enableAdaptiveOptimization(true);
            std::cerr << "Using adaptive optimization - analyzing code characteristics to determine optimal strategy" << std::endl;

            optimizer.optimize(root);
            std::cerr << "[main] after optimizer" << std::endl;
        }

        // 生成RISC-V汇编代码
        std::cerr << "[main] before codeGen.generate" << std::endl;
        CodeGenerator codeGen;
        codeGen.generate(root);
        std::cerr << "[main] after codeGen.generate" << std::endl;
        // 只输出汇编代码到stdout
        std::cerr << "[main] before codeGen.printCode" << std::endl;
        codeGen.printCode();
        std::cerr << "[main] after codeGen.printCode" << std::endl;
        // delete root; // 不需要手动delete，ASTNode用unique_ptr管理
    }

    // 关闭文件（如果是从文件读取的话）
    if (!inputFile.empty() && yyin != stdin) {
        std::cerr << "[main] before fclose" << std::endl;
        fclose(yyin);
        std::cerr << "[main] after fclose" << std::endl;
    }
    std::cerr << "[main] leave main()" << std::endl;
    return 0;
}

//./compiler < test7.c > test7.s
//./compiler < test18.c > test18.s
//./compiler < test16.3.c > test16.3.s
//./compiler < test17.c > test17.s 2> debug17.log
//./compiler < test7.2.c > test7.2.s 2> debug7.2.log
//./compiler < test8.c > test8.s 2> debug8.log
//./compiler < test17.3.c > test17.3.s 2> debug17.3.log
//./compiler < test19.c > test19.s  2> debug19.log
